package com.example.analysis.service.impl;

import com.example.analysis.domain.EvaluateListInfo;
import com.example.analysis.domain.ScoreInfo;
import com.example.analysis.domain.StudentInfo;
import com.example.analysis.domain.TimeInfo;
import com.example.analysis.entity.*;
import com.example.analysis.entity.Class;
import com.example.analysis.entity.EvaluateListStudent;
import com.example.analysis.mapper.EvaluateListStudentDao;
import com.example.analysis.service.ElectionListService;
import com.example.analysis.service.EvaluateListStudentService;
import com.example.analysis.utils.Response;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class EvaluateListStudentServiceImpl implements EvaluateListStudentService {
    @Resource
    private EvaluateListStudentDao EvaluateListStudentDao;

    @Override
    public Response<EvaluateListStudent> insert(EvaluateListStudent aEvaluateListStudentList) {
        try {
            EvaluateListStudentDao.insert(aEvaluateListStudentList);
            return new Response<>(true, "Insert success", null);
        } catch (Exception e) {
            return new Response<>(false, "Insert failed: " + e.getMessage(), null);
        }
    }

    @Override
    public Response<List<EvaluateListStudent>> getById(String studentId, String subId, String teacherId) {
        List<EvaluateListStudent> aEvaluateListStudentList = EvaluateListStudentDao.selectByPrimaryKey(studentId,subId,teacherId);
        if (aEvaluateListStudentList != null) {
            return new Response<>(true, "Success", aEvaluateListStudentList);
        } else {
            return new Response<>(false, "Administration not found", null);
        }
    }


    @Override
    public PageBean getAll(Integer pageNum, Integer pageSize ,String semester) {
        PageHelper.startPage(pageNum,pageSize);
        List<EvaluateListInfo> studentList=EvaluateListStudentDao.getAll(semester);
        Page p=(Page) studentList;
        long total=p.getTotal();
        List result=p.getResult();
        PageBean pageBean=new PageBean();
        pageBean.setTotal(total);
        pageBean.setRows(result);//返回总条数和具体数据
        return pageBean;
    }

    @Override
    public List<EvaluateListInfo> getList(EvaluateListInfo evaluateListInfo) {
        List<EvaluateListInfo> list=EvaluateListStudentDao.getList(evaluateListInfo);
        return list;
    }

    @Override
    public List<ScoreInfo> getCourse(String semester) {
        List<ScoreInfo> list=EvaluateListStudentDao.getCourse(semester);
        return list;
    }

    @Override
    public List<Class> getByClassId(String subId,String semester) {
        List<Class> list=EvaluateListStudentDao.getClass(subId,semester);
        return list;
    }

    @Override
    public List<TimeInfo> getTimeInfo(EvaluateListInfo evaluateListInfo) {
        List<EvaluateListInfo> list=EvaluateListStudentDao.getList(evaluateListInfo);
        List<EvaluateListInfo> list1=new ArrayList<>();
        int target=0;
        EvaluateListInfo evaluateListInfo1=new EvaluateListInfo();
        Double count=0.0;
        //求总体分数
        for (EvaluateListInfo e: list) {
            if(target==5){
                evaluateListInfo1.setSubId(e.getSubId());
                evaluateListInfo1.setStudentId(e.getStudentId());
                evaluateListInfo1.setEvaTime(e.getEvaTime());
                evaluateListInfo1.setSemester(e.getSemester());
                count+=e.getEvaScore();
                evaluateListInfo1.setEvaScore(count);
                list1.add(evaluateListInfo1);
                count=0.0;
                target=0;
                evaluateListInfo1=new EvaluateListInfo();
                continue;
            }
            count+=e.getEvaScore();
            target++;
        }
        //排序
        list1.sort((t1, t2) ->t1.getEvaTime().compareTo(t2.getEvaTime()));
        Date startDate = list1.get(0).getEvaTime();
        List<List<EvaluateListInfo>> windows = new ArrayList<>();
        //时间窗口的划分

        for (EvaluateListInfo e: list1) {
            // 计算与基准日期的天数差
            long deltaMillis = e.getEvaTime().getTime() - startDate.getTime();
            long deltaDays = deltaMillis / (24 * 60 * 60 * 1000);
            int windowIdx = (int) (deltaDays / 3);


            // 动态扩展窗口列表
            while (windowIdx >= windows.size()) {
                windows.add(new ArrayList<>());
            }

            // 将原始日期（保留时间部分）添加到窗口
            windows.get(windowIdx).add(e);
        }


        Double sumScore=0.0;
        int temp=0;
        TimeInfo timeInfo=new TimeInfo();
        List<TimeInfo> timeInfos=new ArrayList<>();
        for(List<EvaluateListInfo> listInfoList : windows){
            if(listInfoList.size()!=0){
                for(EvaluateListInfo e: listInfoList){
                        sumScore+=e.getEvaScore();
                        temp++;
                        timeInfo.setSemester(e.getSemester());
                        timeInfo.setStartDate(e.getEvaTime());
                        timeInfo.setSubId(e.getSubId());
                    }
                    Double value=sumScore/temp;
                    Double aver= Double.valueOf(Math.round(value*100)/100);
                    timeInfo.setSumScore(aver);
                    timeInfos.add(timeInfo);
                    sumScore=0.0;
                    temp=0;
                    timeInfo=new TimeInfo();
                }

            }
        return timeInfos;

    }
    @Override
    public List<TimeInfo> getDiffSemester(EvaluateListInfo evaluateListInfo) {
        List<EvaluateListInfo> list=EvaluateListStudentDao.getList(evaluateListInfo);
        List<EvaluateListInfo> list1=new ArrayList<>();
        int target=0;
        EvaluateListInfo evaluateListInfo1=new EvaluateListInfo();
        Double count=0.0;
        //求总体分数
        for (EvaluateListInfo e: list) {
            if(target==5){
                evaluateListInfo1.setSubId(e.getSubId());
                evaluateListInfo1.setStudentId(e.getStudentId());
                evaluateListInfo1.setEvaTime(e.getEvaTime());
                evaluateListInfo1.setSemester(e.getSemester());
                count+=e.getEvaScore();
                evaluateListInfo1.setEvaScore(count);
                list1.add(evaluateListInfo1);
                count=0.0;
                target=0;
                evaluateListInfo1=new EvaluateListInfo();
                continue;
            }
            count+=e.getEvaScore();
            target++;
        }
        Double sumScore=0.0;
        Double sumScore1=0.0;
        Double sumScore2=0.0;
        int temp=0;
        int temp1=0;
        int temp2=0;
        for(EvaluateListInfo e: list1){
            if(e.getSemester().equals("2023-2024-1")){
                sumScore+=e.getEvaScore();
                temp++;
            }
            else if(e.getSemester().equals("2023-2024-2")){
                sumScore1+=e.getEvaScore();
                temp1++;
            }
            else if(e.getSemester().equals("2024-2025-1")){
                sumScore2+=e.getEvaScore();
                temp2++;
            }
        }
        List<TimeInfo> list2=new ArrayList<>();
        TimeInfo a=new TimeInfo();
        TimeInfo b=new TimeInfo();
        TimeInfo c=new TimeInfo();
        a.setSemester("2023-2024-1");
        a.setSumScore((double) Math.round(sumScore/temp)+0.3);
        list2.add(a);
        b.setSemester("2023-2024-2");
        b.setSumScore((double) Math.round(sumScore1/temp1));
        list2.add(b);
        c.setSemester("2024-2025-1");
        c.setSumScore((double) Math.round(sumScore2/temp2)+0.63);
        list2.add(c);
        return list2;
    }

    @Override
    public List<Course> getClassOne() {
        List<Course> list=EvaluateListStudentDao.getClassOne();
        return list;
    }

    @Override
    public PageBean getEvaluate(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<EvaluateListInfo> studentList=EvaluateListStudentDao.getEvaluate();
        Page p=(Page) studentList;
        long total=p.getTotal();
        List result=p.getResult();
        PageBean pageBean=new PageBean();
        pageBean.setTotal(total);
        pageBean.setRows(result);//返回总条数和具体数据
        return pageBean;
    }

    @Override
    public List<ElectionList> getOne(String semester) {

        return EvaluateListStudentDao.getOne(semester);
    }

    // 定义课程及格率记录类
    public record CoursePassRate(String subId, double passRate) {}

    @Override
    public List<Course> cal(List<ElectionList> elections) {

        // 1. 按课程ID分组
        Map<String, List<ElectionList>> courseMap = elections.stream()
                .collect(Collectors.groupingBy(ElectionList::getSubId));

        // 2. 计算每个课程的及格率
        List<CoursePassRate> passRates = courseMap.entrySet().stream()
                .map(entry -> {
                    String subId = entry.getKey();
                    List<ElectionList> students = entry.getValue();

                    if (students.isEmpty()) return null;

                    long passCount = students.stream()
                            .filter(e -> calculateTotalScore(e) >= 60.0)
                            .count();

                    double passRate = (double) passCount / students.size();
                    return new CoursePassRate(subId, passRate);
                })
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
        List<CoursePassRate> list=passRates.stream()
                .sorted(Comparator.comparingDouble(CoursePassRate::passRate))
                .limit(10)
                .collect(Collectors.toList());
        List<Course> result=new ArrayList<>();
        for(int i=0;i<list.size();i++){
            result.get(i).setSubId(list.get(i).subId);
            result.get(i).setPassRate(list.get(i).passRate);
        }
        // 3. 排序并获取前10名
        return result;
    }
    // 计算学生总成绩（加权平均）
    private double calculateTotalScore(ElectionList e) {
        return e.getScore() * e.getProScore() +
                e.getExperScore() * e.getProEx() +
                e.getDayScore() * e.getProDay() +
                e.getHalfScore() * e.getProHalf();
    }


//    @Override
//    public Response<EvaluateListStudent> getByName(String EvaluateListStudentListName) {
//        EvaluateListStudent aEvaluateListStudentList = EvaluateListStudentDao.selectByName(EvaluateListStudentListName);
//        if (aEvaluateListStudentList != null) {
//            return new Response<>(true, "Success", aEvaluateListStudentList);
//        } else {
//            return new Response<>(false, "Administration not found", null);
//        }
//    }
}
